package com.liuchang.controller;

import com.liuchang.req.DeleteFileReq;
import com.liuchang.req.DownloadFileReq;
import com.liuchang.utils.FastDfsClientUitl;
import com.liuchang.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;


/**
 * @author :liuchang
 * @description:TODO
 * @date :2021/8/15 20:00
 */
@RestController
@RequestMapping("/api/fastdfs")
@Api(tags = "操作文件Apis", description = "提供文件相关的 Rest API")
public class FileController {

    @Autowired
    public FastDfsClientUitl fastDfsClientUitl;


    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public Result upload(MultipartFile file) throws Exception{
        String url = fastDfsClientUitl.uploadFile(file);
        Result<String> result = new Result<>(true, "", url);
        return result;
    }

    @GetMapping("/download")
    @ApiOperation("下载文件")
    public Result download(@Valid DownloadFileReq req, HttpServletResponse response) throws IOException {
        String fileUrl = req.getFileUrl();
        fastDfsClientUitl.downLoad(fileUrl, response);

        Result result = new Result(true, null, null);
        return result;
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除文件")
    public Result delete(@Valid DeleteFileReq req) {
        String fileUrl = req.getFileUrl();
        String message = fastDfsClientUitl.deleteFile(fileUrl);
        Result<String> result = new Result<>(true, message, null);
        return result;
    }
}
